package com.lsp.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 读取配置文件
 */
public final class PropertiesUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);

    public static Properties loadProperties(String fileName){
        Properties properties = null;
        InputStream inputStream = null;
            try {

                inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
                if(inputStream == null){
                    throw  new FileNotFoundException(fileName + "file is not found");
                }
                properties = new Properties();
                properties.load(inputStream);
            } catch (IOException e) {
                LOGGER.error("load properties file failure ",e);
            } finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        LOGGER.error("close input stream failure", e);
                    }
                }
            }
        return properties;
    }

    public static String getString(Properties props, String key) {
        return getString(props,key,"");
    }

    private static String getString(Properties props, String key, String defaultValue) {
        String value = defaultValue;
        if(props.containsKey(key)){
            value = props.getProperty(key);
        }
        return value;
    }
}
